//
//  SaleSituationViewController.m
//  IpadTestB
//
//  Created by edianzu on 2017/7/4.
//  Copyright © 2017年 ruilai. All rights reserved.
//

#import "SaleSituationViewController.h"
#import "ChildListCell.h"
#import "BuildNewTestViewController.h"
#import "SalePersonDataViewController.h"
@interface SaleSituationViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) NSMutableDictionary * allDataDictionary;
@property (nonatomic,assign) NSInteger rightNowInteger;
@property (nonatomic,strong)BaseAlertView * alertView;
@property (nonatomic,strong) NSNumber * proid;//用于营销场景
@property (nonatomic,copy)NSIndexPath* RindexPath;
@end

@implementation SaleSituationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"营销场景";
    self.view.backgroundColor = UIColorFromRGB(241, 246, 248);
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont boldSystemFontOfSize:23*AutoScaleHorizontal],
       NSForegroundColorAttributeName:[UIColor whiteColor]}];
    ////////////////左按钮
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    leftBtn.frame = CGRectMake(0, 0, 35,35);
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"navBack"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftBarBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftBarBtn = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];;
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = 15;
    //将两个BarButtonItem都返回给NavigationItem
    self.navigationItem.leftBarButtonItems = @[spaceItem,leftBarBtn];
    
    //创建右边按钮
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 140,35);
    rightBtn.layer.cornerRadius =10;
    rightBtn.backgroundColor = [UIColor whiteColor];
    //    [rightBtn setImage:[UIImage imageNamed:@"navRightBtn"] forState:UIControlStateNormal];
    [rightBtn setTitle:@"十  新建测试" forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:20*AutoScaleHorizontal];
    [rightBtn setTitleColor:UIColorFromRGB(26, 167, 157) forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightBarBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightBarBtn = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];;
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItemm = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    //将宽度设为负值
    spaceItemm.width = -5;
    //将两个BarButtonItem都返回给NavigationItem
    self.navigationItem.rightBarButtonItems = @[spaceItemm,rightBarBtn];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getData];
}

-(void)getData{
    self.childNameArr = [[NSMutableArray alloc]init];
    self.weekArr = [[NSMutableArray alloc]init];
    self.monthArr = [[NSMutableArray alloc]init];
    
    //获取全部数据
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    NSString* str = [user objectForKey:@"AllData"];
    NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
    _allDataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    NSMutableArray * testArray = [NSMutableArray arrayWithArray: [_allDataDictionary objectForKey:@"TestResult"]];
    NSMutableArray * proArr  = [[NSMutableArray alloc]init];
    proArr = [_allDataDictionary objectForKey:@"Programs"];//营销计划的数据 用type+id判断
    _proid = [[NSNumber alloc]init];
    for (NSMutableDictionary * dic in proArr) {
        if ([[dic objectForKey:@"Type"]isEqual:@0]) {
            _proid = [dic objectForKey:@"Id"];
        }
    }
////    //冒泡时间倒叙
//    NSLog(@"startTime");
//    for (int  i =0; i<[testArray count]-1; i++) {
//        
//        for (int j = i+1; j<[testArray count]; j++) {
//            NSMutableDictionary * dictx = testArray[i];
//            NSMutableDictionary * dict = [dictx objectForKey:@"master"];
//            
//            NSMutableDictionary * dictxx = testArray[j];
//            NSMutableDictionary * dict1 = [dictxx objectForKey:@"master"];
//            if ([[dict objectForKey:@"Id"]integerValue]<[[dict1 objectForKey:@"Id"]integerValue]) {
//                //交换
//                [testArray exchangeObjectAtIndex:i withObjectAtIndex:j];
//            }
//            
//        }
//        
//    }
//    NSLog(@"stopTime");
    
    //将负数放在最前面
    for (NSMutableDictionary * dict in testArray.reverseObjectEnumerator) {
        NSMutableDictionary * dic = [dict objectForKey:@"master"];
        if ([[dic objectForKey:@"Id"]integerValue]<0) {
            [testArray removeObject:dict];
            [testArray insertObject:dict atIndex:0];
        }
    }
    for (NSMutableDictionary * dict in testArray) {
        NSMutableDictionary * dic = [dict objectForKey:@"master"];
        if ([[dic objectForKey:@"ProgramId"]isEqual:_proid]) {
            ChildModel * mod = [ChildModel modelWithDictionary:dic];
           //获取时间
            NSString * time1 = [mod.CreateTime substringWithRange:NSMakeRange(0, 10)];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyy-MM-dd";
            NSDate *creat = [formatter dateFromString:time1]; // 传入的时间
            NSString * finalTime = [self dateToDetailOld:creat];
            
            if ([finalTime integerValue] > 7) {
                [self.monthArr addObject:mod];
            }else{
                [self.weekArr addObject:mod];
            }
        }
    }
        [self.childNameArr addObject:self.weekArr];
        [self.childNameArr addObject:self.monthArr];
    
    [user synchronize];
    [self creatUI];
    
}

-(void)creatUI{
    
    if (self.weekArr.count ==0 && self.monthArr.count ==0) {
        UILabel * noDataLabel = [[UILabel alloc]init];
        noDataLabel.text = @"还没有孩子";
        noDataLabel.textColor = [UIColor blackColor];
        noDataLabel.font = [UIFont boldSystemFontOfSize:25*AutoScaleHorizontal];
        [self.view addSubview:noDataLabel];
        [noDataLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self.view.mas_centerX);
            make.centerY.mas_equalTo(self.view.mas_centerY);
            
        }];
    }else{
    self.myTableView = [[UITableView alloc]init];
    self.myTableView.backgroundColor =UIColorFromRGB(241, 244, 248);
    self.myTableView.delegate =self;
    self.myTableView.dataSource =self;
    self.myTableView.showsVerticalScrollIndicator =NO;
    //无分割线
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //多余的CELL 隐藏
    self.myTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.myTableView registerClass:[ChildListCell class] forCellReuseIdentifier:@"ChildListCell"];
    [self.view addSubview:self.myTableView];
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).with.offset(50*AutoScaleHorizontal);
        make.right.mas_equalTo(self.view.mas_right).with.offset(-50*AutoScaleHorizontal);
        make.top.mas_equalTo(self.view.mas_top).with.offset(30*AutoScaleVertical);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT-100*AutoScaleHorizontal));
    }];
    }
}

#pragma mark tableViewDelegate
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (self.weekArr.count != 0 && self.monthArr.count ==0) {
        UIView * view = [[UIView alloc]init];
        view.backgroundColor = UIColorFromRGB(241, 246, 248);
        UILabel * label = [[UILabel alloc]init];
        label.font = [UIFont boldSystemFontOfSize:20*AutoScaleHorizontal];
        label.textColor = [UIColor blackColor];
            label.text = @"一周内";
        [view addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(view.mas_left);
            make.centerY.mas_equalTo(view.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(150*AutoScaleHorizontal, 20*AutoScaleVertical));
        }];
        return view;
    }else if(self.weekArr.count == 0 && self.monthArr.count !=0){
        UIView * view = [[UIView alloc]init];
        view.backgroundColor = UIColorFromRGB(241, 246, 248);
        UILabel * label = [[UILabel alloc]init];
        label.font = [UIFont boldSystemFontOfSize:20*AutoScaleHorizontal];
        label.textColor = [UIColor blackColor];
        label.text = @"一个月内";
        [view addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(view.mas_left);
            make.centerY.mas_equalTo(view.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(150*AutoScaleHorizontal, 20*AutoScaleVertical));
        }];
        return view;
    }else{
    UIView * view = [[UIView alloc]init];
    view.backgroundColor = UIColorFromRGB(241, 246, 248);
    UILabel * label = [[UILabel alloc]init];
    label.font = [UIFont boldSystemFontOfSize:20*AutoScaleHorizontal];
    label.textColor = [UIColor blackColor];
    if (section == 0) {
        label.text = @"一周内";
    }else{
        label.text = @"一个月内";
    }
    [view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(view.mas_left);
        make.centerY.mas_equalTo(view.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(150*AutoScaleHorizontal, 20*AutoScaleVertical));
    }];
    return view;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30*AutoScaleVertical;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60*AutoScaleVertical;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (self.weekArr.count != 0 && self.monthArr.count ==0) {
        return 1;
    }else if(self.weekArr.count == 0 && self.monthArr.count !=0){
        return 1;
    }else{
    
        return 2;
}
}
//
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.weekArr.count != 0 && self.monthArr.count ==0) {
        return self.weekArr.count;
    }else if(self.weekArr.count == 0 && self.monthArr.count !=0){
        return self.monthArr.count;
    }else{
        
        return  [[self.childNameArr objectAtIndex:section]count];
    }
    
    
    
}
//
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ChildListCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ChildListCell"];
    if (cell ==nil) {
        cell = [[ChildListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ChildListCell"];
    }
    if (self.weekArr.count != 0 && self.monthArr.count ==0) {
        [cell setUiWithSaleModel:self.weekArr[indexPath.row] andinteger:indexPath];
    }else if(self.weekArr.count == 0 && self.monthArr.count !=0){
        [cell setUiWithSaleModel:self.monthArr[indexPath.row] andinteger:indexPath];
    }else{
        
        [cell setUiWithSaleModel:self.childNameArr[indexPath.section][indexPath.row] andinteger:indexPath];
    }
    __weak typeof(self) weak_self = self;
    cell.callDelete = ^(NSIndexPath* indexP) {
        NSLog(@"开始删除%d",indexP.row);
        [weak_self creatDeleteViewWithIndex:indexP];
    };
    
    
    
    return  cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    SalePersonDataViewController * pvc = [[SalePersonDataViewController alloc]init];
    
    if (self.weekArr.count != 0 && self.monthArr.count ==0) {
        pvc.model = self.weekArr[indexPath.row];
    }else if(self.weekArr.count == 0 && self.monthArr.count !=0){
        pvc.model = self.monthArr[indexPath.row];
    }else{
        
        pvc.model = [self.childNameArr objectAtIndex:indexPath.section][indexPath.row];
    }
    
    [self.navigationController pushViewController:pvc animated:YES];
}


#pragma mark  删除营销孩子
-(void)creatDeleteViewWithIndex:(NSIndexPath*)indexpath{
    self.RindexPath = indexpath;
    ChildModel * mod = [[ChildModel alloc]init];
    if (self.weekArr.count!= 0 && self.monthArr.count == 0) {
        mod = self.weekArr[indexpath.row];
    }else if (self.weekArr.count ==0 && self.monthArr.count != 0){
        mod = self.monthArr[indexpath.row];
    }else{
        if (indexpath.section ==0) {
            mod = self.weekArr[indexpath.row];
        }else{
       mod = self.monthArr[indexpath.row];
        }
    }
    
    
    //蒙版
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _backView.backgroundColor = [UIColor blackColor];
    _backView.alpha = 0.52;
    [window addSubview:_backView];
    
    _alertView = [[BaseAlertView alloc]init];
    _alertView.infomationLabel.text = @"是否删除该孩子?";
    [window addSubview:_alertView];
    [_alertView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(window.mas_centerX);
        make.centerY.mas_equalTo(window.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(500*AutoScaleHorizontal, 250*AutoScaleVertical));
    }];
    
    UILabel * planname = [[UILabel alloc]init];
    planname.text =[NSString stringWithFormat:@"孩子姓名:%@",mod.ChildName];
    [planname setTextAlignment:NSTextAlignmentCenter];
    planname.textColor = UIColorFromRGB(81, 81,81);
    planname.font = [UIFont systemFontOfSize:18*AutoScaleHorizontal];
    [_alertView addSubview:planname];
    [planname mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_alertView.infomationLabel.mas_bottom).with.offset(5*AutoScaleVertical);
        make.centerX.mas_equalTo(_alertView.infomationLabel.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(400*AutoScaleHorizontal, 20*AutoScaleVertical));
    }];
    
    [_alertView.yesBtn addTarget:self action:@selector(pressAlertYesWithindex:) forControlEvents:UIControlEventTouchUpInside];
    [_alertView.noBtn addTarget:self action:@selector(pressAlertNo) forControlEvents:UIControlEventTouchUpInside];
}
-(void)pressAlertYesWithindex:(NSIndexPath*)indexpath{
    NSLog(@"确定删除");
    indexpath = self.RindexPath;
    ChildModel * mod = [[ChildModel alloc]init];
    if (self.weekArr.count!= 0 && self.monthArr.count == 0) {
        mod = self.weekArr[indexpath.row];
        for (ChildModel * model in self.weekArr.reverseObjectEnumerator) {
            if (model == mod) {
                [self.weekArr removeObject:model];
            }
        }
        
    }else if (self.weekArr.count ==0 && self.monthArr.count != 0){
        mod = self.monthArr[indexpath.row];
        for (ChildModel * model in self.monthArr.reverseObjectEnumerator) {
            if (model == mod) {
                [self.monthArr removeObject:model];
            }
        }
        
    }else{
        if (indexpath.section ==0) {
            mod = self.weekArr[indexpath.row];
            for (ChildModel * model in self.weekArr.reverseObjectEnumerator) {
                if (model == mod) {
                    [self.weekArr removeObject:model];
                }
            }
            
        }else{
            mod = self.monthArr[indexpath.row];
            for (ChildModel * model in self.monthArr.reverseObjectEnumerator) {
                if (model == mod) {
                    [self.monthArr removeObject:model];
                }
            }
        }
    }
    [self.childNameArr removeAllObjects];
    [self.childNameArr addObject:self.weekArr];
    [self.childNameArr addObject:self.monthArr];
    
    //更新数据源
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    NSMutableArray * arr = [_allDataDictionary objectForKey:@"TestResult"];
//    NSMutableDictionary * dic = arr[indexpath];
    
    for (NSMutableDictionary * dict in arr.reverseObjectEnumerator) {
        NSMutableDictionary * masterdic = [dict objectForKey:@"master"];
        if ([[masterdic objectForKey:@"Id"] isEqual:mod.Id]) {
            [arr removeObject:dict];
        }
    }
    
    [_allDataDictionary removeObjectForKey:@"TestResult"];
    [_allDataDictionary setObject:arr forKey:@"TestResult"];
    NSData * data = [NSJSONSerialization dataWithJSONObject:_allDataDictionary options:NSJSONWritingPrettyPrinted error:nil];
    NSString * allStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    //
    [user removeObjectForKey:@"AllData"];
    [user setObject:allStr forKey:@"AllData"];
    [user synchronize];
    
    if (mod.Id>0) {
        
        if ([user objectForKey:@"deleteMasterArray"] !=nil) {
            
            
            NSString* str = [user objectForKey:@"deleteMasterArray"];
            //    NSLog(@"eee===%@",str);
            NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
            NSMutableDictionary * dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
            NSMutableArray * allClassArr  = [[NSMutableArray alloc]init];
            allClassArr = [dict objectForKey:@"deleteMasterArray"];
            [allClassArr addObject:mod.Id];
            
            [dict removeObjectForKey:@"deleteMasterArray"];
            [dict setObject:allClassArr forKey:@"deleteMasterArray"];
            NSData * data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
            NSString * allStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            [user removeObjectForKey:@"deleteMasterArray"];
            [user setObject:allStr forKey:@"deleteMasterArray"];
            [user synchronize];
            
        }else{
            NSMutableArray * DCA = [[NSMutableArray alloc]init];
            [DCA addObject:mod.Id];
            NSMutableDictionary * dcd = [[NSMutableDictionary alloc]init];
            [dcd setObject:DCA forKey:@"deleteMasterArray"];
            NSData * data = [NSJSONSerialization dataWithJSONObject:dcd options:NSJSONWritingPrettyPrinted error:nil];
            NSString* deleteChild = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            [user setObject:deleteChild forKey:@"deleteMasterArray"];
            [user synchronize];
        }
    }
    [_backView removeFromSuperview];
    [self.alertView removeFromSuperview];
    [self.myTableView reloadData];
    
    
}
-(void)pressAlertNo{
    NSLog(@"取消删除");
    [_backView removeFromSuperview];
    [self.alertView removeFromSuperview];
}



#pragma mark 左右导航栏按钮方法
-(void)leftBarBtnClicked{
    NSLog(@"左按钮");
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)rightBarBtnClicked{
    NSLog(@"新建测试ING");
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    [user removeObjectForKey:@"finalSaleDic"];
    BuildNewTestViewController * bvc = [[BuildNewTestViewController alloc]init];
    [self.navigationController pushViewController:bvc animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
